package com.openness.spider.template;

import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;

import com.openness.spider.Html;
import com.openness.spider.commons.UrlUtil;
import com.openness.spider.template.netbase.MoneyTemplate;
import com.openness.spider.template.sina.FinanceTemplate;
import com.openness.spider.template.sina.NewsTemplate;
import com.openness.spider.template.sina.TechTemplate;
import com.openness.spider.template.sohu.BusinessTemplate;
import com.openness.spider.template.sohu.ItTemplate;

/**
 * @author Rain
 * @version 2013-6-26 下午4:20:39
 */

public class TemplateUtil {

	private static final Map<String, Map<String, Template>> TEMPLATES = new HashMap<String, Map<String, Template>>();

	static {
		Map<String, Template> sina = new HashMap<String, Template>();

		sina.put("news", new NewsTemplate());
		sina.put("finance", new FinanceTemplate());
		sina.put("tech", new TechTemplate());

		TEMPLATES.put("sina.com.cn", sina);

		Map<String, Template> qq = new HashMap<String, Template>();

		qq.put("news", new com.openness.spider.template.qq.NewsTemplate());
		qq.put("finance", new com.openness.spider.template.qq.FinanceTemplate());
		qq.put("tech", new com.openness.spider.template.qq.TechTemplate());

		TEMPLATES.put("qq.com", qq);

		Map<String, Template> sohu = new HashMap<String, Template>();

		sohu.put("news", new com.openness.spider.template.sohu.NewsTemplate());
		sohu.put("business", new BusinessTemplate());
		sohu.put("it", new ItTemplate());

		TEMPLATES.put("sohu.com", sohu);

		Map<String, Template> netbase = new HashMap<String, Template>();

		netbase.put("news",
				new com.openness.spider.template.netbase.NewsTemplate());
		netbase.put("money", new MoneyTemplate());
		netbase.put("tech",
				new com.openness.spider.template.netbase.TechTemplate());

		TEMPLATES.put("163.com", netbase);
	}

	public static Html parse(String url, String html) throws Exception {
		if (url == null || url.isEmpty() || html == null || html.isEmpty()) {
			return null;
		}

		String domain = UrlUtil.getDomain(url);

		String subDomain = UrlUtil.getSubDomain(url);

		Map<String, Template> domainTemplates = TEMPLATES.get(domain);
		if (domainTemplates == null || domainTemplates.size() == 0) {
			return null;
		}

		Template subDomainTemplate = domainTemplates.get(subDomain);
		if (subDomainTemplate == null) {
			return null;
		}

		return subDomainTemplate.parse(url, html);
	}

	public static void main(String[] args) throws Exception {
		String url = "http://ent.sina.com.cn/s/m/2013-06-25/18333950076.shtml";

		String source = Jsoup.connect(url).get().html();

		Html html = TemplateUtil.parse(url, source);

		System.out.println(html.toString());
	}
}
